﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bluyel.Core
{
    /// <summary>
    /// To convert value from a type to another.
    /// </summary>
    public class ValueConverter
    {
        TypeMgrBase _typeMgr;

        TypeFinderBase _typeFinder;

        ValueBuilder _valueBuilder;

        PhyConverter _phyConverter;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ValueConverter(TypeMgrBase typeMgr, TypeFinderBase typeFinder, ValueBuilder valueBuilder)
        {
            _typeMgr = typeMgr;
            _typeFinder = typeFinder;
            _valueBuilder = valueBuilder;

            _phyConverter = new PhyConverter(_typeMgr, _typeFinder, _valueBuilder);
        }

        public PhyConverter PhyConverter
        { get { return _phyConverter; } }

        /// <summary>
        /// Convert a string value to a ValueString object.
        /// </summary>
        /// <param name="val"></param>
        /// <param name="valueInt"></param>
        /// <returns></returns>
        public bool ToValueString(string val, out ValueString valueString)
        {
            valueString = null;

            if (val==null)
                return false;

            valueString = _valueBuilder.CreateValueString(val);
            return true;
        }

        /// <summary>
        /// Convert a string value to a ValueInt object.
        /// </summary>
        /// <param name="val"></param>
        /// <param name="valueInt"></param>
        /// <returns></returns>
        public bool ToValueInt(string val, out ValueInt valueInt)
        {
            valueInt = null;

            if (string.IsNullOrWhiteSpace(val))
                return false;

            int valInt;
            if (!int.TryParse(val, out valInt))
                return false;

            valueInt = _valueBuilder.CreateValueInt(valInt);
            return true;
        }

        /// <summary>
        /// Convert a string value to a ValueDouble object.
        /// </summary>
        /// <param name="val"></param>
        /// <param name="valueInt"></param>
        /// <returns></returns>
        public bool ToValueDouble(string val, out ValueDouble valueDouble)
        {
            valueDouble = null;

            if (string.IsNullOrWhiteSpace(val))
                return false;

            double valDouble;
            if (!double.TryParse(val, out valDouble))
                return false;

            valueDouble = _valueBuilder.CreateValueDouble(valDouble);
            return true;
        }
    }

}
